const DB = require('../config/sequelize')
const redisConfig = require('../config/redisConfig.ts')
const RandomTool = require('../utils/RandomTool')
const SecretTool = require('../utils/SecretTool')
const BackCode = require('../utils/BackCode.js')
const CodeEnum = require('../utils/CodeEnum.js')

const UserService = {
  register: async (phone, code) => {
    // 手机号是否存在
    let exitPhone = await DB.Account.findAll({
      where: { phone }
    })
    if (exitPhone.length > 0) {
      // return { code:'-1',msg:'账号已存在' }
      return BackCode.buildError(CodeEnum.ACCOUNT_REPEAT)

    }
    // 获取redis中的验证码和用户的是否一致
    if (phoneRedis = await redisConfig.exists('register:code:' + phone)) {
      let coderedis = (await redisConfig.get('register:code:' + phone)).split('_')[1]
      if (code !== coderedis) {
        // return { code:'-1', msg:'短信验证码错误' }
        return BackCode.buildError({ msg: '短信验证码错误' })
      }
    } else {
      // return { code:'-1', msg:'请先获取短信验证码' }
      return BackCode.buildError({ msg: '请先获取短信验证码' })
    }
    // 生成头像 昵称
    const avatar = RandomTool.randomAvatar()
    const name = RandomTool.randomName()

    // 生成token 7天过期
    let user = { avatar, name, phone }
    const token = SecretTool.jwtSign(user, '168h')

    // 插入数据库
    await DB.Account.create({ name, avatar, phone })
    return { code: 0, data: `Bearer ${token}` }
  },
  login: async (req) => {
    const phone = req.body?.phone
    const password= req.body?.password
    const code= req.body?.code
    if (!(phone && (password || code))) return BackCode.buildError({ msg:'缺少必要参数'})
    // raw: true，返回的值为原始数据，否则默认为false，数据是经过sequelize装饰过的，但直接返回给前
    let userInfo = await DB.Account.findAll({ where: { phone }, raw: true })
    if (userInfo.length === 0) return BackCode.buildResult(CodeEnum.ACCOUNT_UNREGISTER)
    // 账号密码登录
    if (password) {
      // 判断密码是否正确
      if (!(SecretTool.md5(password) == userInfo[0].password)) {
        return BackCode.buildResult(CodeEnum.ACCOUNT_PWD_ERROR)
      }
    } else {
      // ⼿机验证码登录
      // 获取redis缓存的code,判断⽤户code是否正确
      let codeExist = await redisConfig.exists('login:code:' + phone)
      if (!codeExist) return BackCode.buildError({msg:'请先获取⼿机验证码'})
      let codeRes = (await redisConfig.get('login:code:' + phone)).split('_')[1]
      // 对⽐⽤户code和reids code
      if (!(code == codeRes)) return BackCode.buildError({msg:'⼿机验证码不正确'})
    }
    // 拼接token的⽤户信息,除去密码
    let user = { ...userInfo[0], password: '' }
    // ⽣成token
    let token = SecretTool.jwtSign(user, '168h')
    return BackCode.buildSuccessAndData(`Bearer ${token}`)
  },
  forget: async (req) => {
    const { phone, password, code } = req.body
    // code 是否在redis里
    const codeRedis = await redisConfig.exists('change:code:' + phone)
    if (!codeRedis) {
      return BackCode.buildError({ msg: '请先获取手机验证码' })
    }
    const redisCodeval = (await redisConfig.get('change:code:' + phone)).split('_')[1]
    if (code !== redisCodeval) return BackCode.buildError({ msg: '手机验证码错误' })
    // 验证码正确 存入数据库
    const pwd = SecretTool.md5(password)
    await DB.Account.update({ password: pwd }, { where: { phone } })
    return BackCode.buildSuccessAndMsg({ msg: '密码修改成功' })
  }
}

module.exports = UserService